package net.asfun.jvalog.domain;

import java.util.Collection;

import javax.jdo.Query;

import com.google.appengine.api.datastore.Key;
import net.asfun.jvalog.po.Unique;
import net.asfun.jvalog.service.Jdoer;
import net.asfun.jvalog.service.JdoerFactory;

public class Unifier {

	public static boolean isUnique(Key model, String property, String value){
		Jdoer<Unique> jdu = JdoerFactory.getUniqueJdo();
		Query query = jdu.prepareQuery();
		query.setFilter("property == prop && value == val");
		query.declareParameters("String prop, String val");
		Collection<Unique> clt = jdu.more(query, property, value);
		for (Unique uni : clt) {
			if ( uni.getModel().getKind().equals(model.getKind())
					&& uni.getModel().getId() != model.getId() ) 
				return false;
		}
		return true;
	}
	
	public static boolean isUnique(String model, String property, String value){
		Jdoer<Unique> jdu = JdoerFactory.getUniqueJdo();
		Query query = jdu.prepareQuery();
		query.setFilter("property == prop && value == val");
		query.declareParameters("String prop, String val");
		Collection<Unique> clt = jdu.more(query, property, value);
		for (Unique uni : clt) {
			if ( uni.getModel().getKind().equals(model) ) 
				return false;
		}
		return true;
	}
	
	public static void setUnique(Key model, String property, String value) {
		Jdoer<Unique> jdu = JdoerFactory.getUniqueJdo();
		Query query = jdu.prepareQuery();
		query.setFilter("property == prop && model == akey");
		query.declareParameters("String prop, com.google.appengine.api.datastore.Key akey");
		Unique uni = jdu.unique(query, property, model);
		if ( uni == null ) {
			uni = new Unique();
			uni.setModel(model);
			uni.setProperty(property);
			uni.setValue(value);
			jdu.save(uni);
		}
		uni.setValue(value);
	}
	
	public static void unsetUnique(Key model, String property) {
		Jdoer<Unique> jdu = JdoerFactory.getUniqueJdo();
		Query query = jdu.prepareQuery();
		query.setFilter("property == prop && model == akey");
		query.declareParameters("String prop, com.google.appengine.api.datastore.Key akey");
		Unique uni = jdu.unique(query, property, model);
		if ( uni != null ) {
			jdu.delete(uni);
		}
	}
}
